package com.bilisummarize.utils;


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import org.apache.http.Header;
import org.apache.http.HttpEntity;

import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * HttpClient工具类
 *
 * @author ZhangYuanqiang
 * @since 2021-06-10
 */
public class HttpUtils {
    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.处理结果，这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGetWithCookie(String url, String SESSDATA) {
        // 创建一个HttpHeaders对象并添加Cookie信息
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.COOKIE, "SESSDATA=" + SESSDATA);

        // 创建一个请求实体，将请求体和头部信息传入
        org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<>(headers);

        // 使用RestTemplate发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

        // 获取响应内容
        String result = response.getBody();
        System.out.println(result);

        return result;
    }


    public static class ResponseData {
        private String responseBody;
        private List<String> cookies;

        public ResponseData(String responseBody, List<String> cookies) {
            this.responseBody = responseBody;
            this.cookies = cookies;
        }

        public String getResponseBody() {
            return responseBody;
        }

        public List<String> getCookies() {
            return cookies;
        }
    }


    /**
     * 发送HttpGet请求（带有COOKIE的返回）
     * @param url
     * @return
     */
    public static ResponseData sendGetWithCookies(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        String responseBody = null;
        List<String> cookies = new ArrayList<String>();

        try {
            response = httpclient.execute(httpget);

            // 获取响应头中的所有 Set-Cookie 字段
            Header[] headers = response.getHeaders("Set-Cookie");
            for (Header header : headers) {
//                cookies.put(header.getName(), header.getValue());
                cookies.add(header.getValue());
            }

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseBody = EntityUtils.toString(entity);
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return new ResponseData(responseBody, cookies);
    }

    /**
     * 发送HttpPost请求
     * @param oauthKey
     * @return
     */
    public static String sendPostForLogin(String oauthKey) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = "https://passport.bilibili.com/qrcode/getLoginInfo";
        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);

        // 设置请求体参数
        String json = "{\"oauthKey\": \"" + oauthKey + "\"}";
        StringEntity entityString = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entityString);

        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpPost);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.处理结果，这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }
}